package com.diyunapp.xilinapp.details;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.AddressBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.me.AddAddressActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by NIDAYE on 2016/7/1.
 */
public class OrderAddressActivity extends StatusBarActivity {
    @Bind(R.id.order_address_goback_ib)
    ImageButton orderAddressGobackIb;
    @Bind(R.id.address_select_rg)
    RadioGroup addressSelectRg;
    @Bind(R.id.address_set_tv)
    TextView addressSetTv;
    @Bind(R.id.address_delete_tv)
    TextView addressDeleteTv;
    @Bind(R.id.address_new_tv)
    TextView addressNewTv;
    @Bind(R.id.address_sv)
    ScrollView addressSv;

    private String addressId = "";
    private List<AddressBean.DatasBean.AddressListBean> myAddressList = new ArrayList<>();
    private int selectAddressID = -1;   //标识选中地址在myFapiaoList中的位置
    private int selectRadBID = -1;      //标识选中地址在RadioGroup中的位置

    private HashMap<Integer, Integer> addressIDHash = new HashMap<>();

    private View headView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_address_layout);
        ButterKnife.bind(this);
        headView = findViewById(R.id.address_set_menubar_inc);
        super.MenuWidget(headView);
        addressId = getIntent().getStringExtra("AddressId");
        if(!addressId.equals("noaddress"))
        {
            getAddressInfo();
        }
        addressSv.scrollTo(0, 0);
    }


    @OnClick({R.id.order_address_goback_ib, R.id.address_set_tv, R.id.address_delete_tv, R.id.address_new_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.order_address_goback_ib:
                finish();
                break;
            case R.id.address_set_tv:
                if(selectAddressID<0)
                {
                    Toast.makeText(getApplicationContext(),"没有可使用的地址信息！",Toast.LENGTH_SHORT).show();
                }
                else {
                    Intent addressInt = new Intent();
                    Bundle seletedAddressBd = new Bundle();
                    seletedAddressBd.putSerializable("SelectedAddress", myAddressList.get(selectAddressID));
                    addressInt.putExtra("AddressBundle", seletedAddressBd);
                    setResult(1, addressInt);
                    finish();
                    //setAddressDefault();
                }
                break;
            case R.id.address_delete_tv:
                if(selectAddressID<0)
                {
                    Toast.makeText(getApplicationContext(),"没有可删除的地址信息！",Toast.LENGTH_SHORT).show();
                }
                else {
                    deleteAddress();
                }
                break;
            case R.id.address_new_tv:
                Intent addInt = new Intent(this, AddAddressActivity.class);
                startActivityForResult(addInt,1);
                break;
        }
    }
    private void displayAddress() {

        addressSelectRg.removeAllViews();
        addressIDHash.clear();

        if(myAddressList.size()<1)
        {
            return;
        }

        for (int i = 0, j = 0; i < myAddressList.size(); i++, j += 4) {
            RadioButton tempButton = new RadioButton(this);
            tempButton.setButtonDrawable(R.drawable.paytype_radiobuttion_selector);           // 设置按钮的样式
            tempButton.setPadding(30, 0, 0, 0);// 设置文字距离按钮四周的距离

            String memberName = myAddressList.get(i).getTrue_name();
            String addressInfo = myAddressList.get(i).getArea_info() + "  " + myAddressList.get(i).getAddress();

            String memberPhone = myAddressList.get(i).getMob_phone();
            if (memberPhone.isEmpty()) {
                memberPhone = myAddressList.get(i).getTel_phone();
            }
            tempButton.setText(memberName + "    " + memberPhone + "\n" + addressInfo);
            tempButton.setLineSpacing(0, 2);
            tempButton.setTextColor(getResources().getColor(R.color.grey_good_evaluate));
            tempButton.setTextSize(13);
            addressSelectRg.addView(tempButton);
            addressIDHash.put(tempButton.getId(), j);
            if (myAddressList.get(i).getAddress_id().equals(addressId)) {
                selectRadBID = j;
            }

            //加上占空的view
            View blankViewUp = new View(this);
            blankViewUp.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
            addressSelectRg.addView(blankViewUp);
            addressIDHash.put(blankViewUp.getId(), j + 1);

            //加上占空的view
            View lineView = new View(this);
            lineView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
            lineView.setBackgroundColor(getResources().getColor(R.color.grey_seperator));
            addressSelectRg.addView(lineView);
            addressIDHash.put(blankViewUp.getId(), j + 2);

            //加上占空的view
            View blankViewDown = new View(this);
            blankViewDown.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 20));
            addressSelectRg.addView(blankViewDown);
            addressIDHash.put(blankViewDown.getId(), j + 3);
        }

        addressSelectRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                selectRadBID = addressIDHash.get(checkedId);
                selectAddressID = selectRadBID / 4;
            }
        });

        ((RadioButton) addressSelectRg.getChildAt(selectRadBID)).setChecked(true);
    }


    private void getAddressInfo() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_address&op=address_list&key=" + MainActivity.myLogin.getLoginkey();
        Log.i("zhangxiaoxidebug", "getAddressInfo url=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(10000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "address_info=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                JSONObject information = resultObject.optJSONObject("datas");
                                JSONArray listArray = information.optJSONArray("address_list");
                                myAddressList.clear();
                                for (int i = 0; i < listArray.length(); i++) {
                                    JSONObject recordObject = listArray.optJSONObject(i);
                                    String address = recordObject.optString("address");
                                    String address_id = recordObject.optString("address_id");
                                    String area_id = recordObject.optString("area_id");
                                    String area_info = recordObject.optString("area_info");
                                    String city_id = recordObject.optString("city_id");
                                    String dlyp_id = recordObject.optString("dlyp_id");
                                    int is_default = recordObject.optInt("is_default");
                                    String member_id = recordObject.optString("member_id");
                                    String mob_phone = recordObject.optString("mob_phone");
                                    String tel_phone = recordObject.optString("tel_phone");
                                    String true_name = recordObject.optString("true_name");

                                    if (addressId.equals(address_id)) {
                                        selectAddressID = i;
                                    }

                                    myAddressList.add(new AddressBean.DatasBean.AddressListBean(address, address_id, area_id, area_info, city_id, dlyp_id, is_default, member_id, mob_phone, tel_phone, true_name));
                                }

                                if(myAddressList.size()<1)
                                {
                                    selectAddressID = -1;
                                    selectRadBID = -1;
                                }

                                displayAddress();
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "读取地址信息失败，请联系客服处理！", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplicationContext(), "读取地址信息失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void deleteAddress() {
        String url = "http://www.xilingou.com/mobile/index.php?act=member_address&op=address_del&key=" +
                MainActivity.myLogin.getLoginkey() + "&address_id=" + myAddressList.get(selectAddressID).getAddress_id();
        Log.i("zhangxiaoxidebug", "deleteAddress url=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "deleteAddress_info=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                JSONObject information = resultObject.optJSONObject("datas");
                                String state = resultObject.optString("datas");
                                if (state.equals("1")) {
                                    Toast.makeText(getApplicationContext(), "地址已删除！", Toast.LENGTH_SHORT).show();
                                    selectAddressID = 0;
                                    selectRadBID = 0;
                                    getAddressInfo();
                                } else {
                                    String error = information.optString("error");
                                    Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            Toast.makeText(getApplicationContext(), "地址删除失败，请联系客服处理！", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        Toast.makeText(getApplicationContext(), "地址删除失败，请检查网络设置！", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("zhangxiaoxidebug", "resultCode = "  + resultCode);
        Log.i("zhangxiaoxidebug", "requestCode = " + requestCode);

        if (resultCode == 1) {
            if (requestCode == 1) {
                addressId = data.getStringExtra("NewAddress");
                getAddressInfo();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
